<template>
  <div class="consultation-container">
    <h1>在线咨询</h1>
    
    <!-- 聊天界面 -->
    <div class="chat-container">
      <!-- 左侧护工列表 -->
      <div class="caregiver-list">
        <h3>护工列表</h3>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索护工"
          clearable
          class="search-input"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-scrollbar height="calc(100vh - 250px)">
          <div 
            class="caregiver-item" 
            v-for="caregiver in filteredCaregivers" 
            :key="caregiver.caregiverId"
            :class="{ active: currentCaregiver?.caregiverId === caregiver.caregiverId }"
            @click="selectCaregiver(caregiver)"
          >
            <el-avatar :size="40" :src="caregiver.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
            <div class="caregiver-info">
              <div class="name">{{ caregiver.name }}</div>
            </div>
          </div>
        </el-scrollbar>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-area">
        <div class="chat-header" v-if="currentCaregiver">
          <el-avatar :size="32" :src="currentCaregiver.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
          <span>{{ currentCaregiver.name }}</span>
        </div>
        <div class="chat-placeholder" v-else>
          <el-empty description="请选择一位护工开始聊天" />
        </div>
        
        <template v-if="currentCaregiver">
          <!-- 聊天记录 -->
          <div class="chat-messages">
            <el-scrollbar height="calc(100vh - 350px)" ref="messageScrollbar" always>
              <div class="message-list">
                <div class="message-item" v-for="msg in currentMessages" :key="msg.messageId">
                  <div class="message-time">{{ formatDateTime(msg.timestamp) }}</div>
                  <div class="message-content" :class="{ 'message-right': msg.senderRole === 0 }">
                    <el-avatar 
                      :size="32" 
                      :src="msg.senderRole === 0 
                        ? 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png' 
                        : (currentCaregiver?.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')" 
                    />
                    <div class="message-bubble">
                      {{ msg.content }}
                    </div>
                  </div>
                </div>
              </div>
            </el-scrollbar>
          </div>

          <!-- 输入框区域 -->
          <div class="input-area">
            <el-input
              v-model="messageInput"
              type="textarea"
              :rows="3"
              placeholder="请输入消息"
              @keyup.enter.ctrl="sendMessage"
            />
            <el-button type="primary" class="send-btn" @click="sendMessage">发送</el-button>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { listMessage, addMessage } from '@/api/message'
import { listCaregiver } from '@/api/caregiver'
import { listConversation, addConversation } from '@/api/conversation'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const searchKeyword = ref('')
const messageInput = ref('')
const currentCaregiver = ref(null)
const caregiverList = ref([])
const currentMessages = ref([])
const currentConversationId = ref(null)
const messageScrollbar = ref(null)

// 过滤护工列表
const filteredCaregivers = computed(() => {
  if (!searchKeyword.value) return caregiverList.value
  
  const keyword = searchKeyword.value.toLowerCase()
  return caregiverList.value.filter(caregiver => 
    caregiver.name.toLowerCase().includes(keyword)
  )
})

// 获取当前登录用户信息
const getCurrentUser = () => {
  if (!userStore.isLoggedIn) {
    userStore.loadUserInfo()
  }
  return {
    userId: userStore.userId,
    username: userStore.username
  }
}

// 获取护工列表
const getCaregiverList = async () => {
  try {
    const res = await listCaregiver({})
    caregiverList.value = res || []
  } catch (error) {
    console.error('获取护工列表失败:', error)
    ElMessage.error('获取护工列表失败，请重试')
  }
}

// 获取会话ID
const getConversationId = async (caregiverId) => {
  const currentUser = getCurrentUser()
  if (!currentUser || !currentUser.userId) {
    console.error('未获取到用户信息')
    return null
  }

  try {
    // 查询患者与护工之间的会话
    const query = {
      userId: currentUser.userId,
      caregiverId: caregiverId
    }
    
    const conversations = await listConversation(query)
    
    if (Array.isArray(conversations) && conversations.length > 0) {
      // 存在会话，返回会话ID
      return conversations[0].conversationId
    } else {
      // 不存在会话，创建新会话
      const newConversation = {
        userId: currentUser.userId,
        caregiverId: caregiverId,
        createTime: new Date().toISOString()
      }
      
      const result = await addConversation(newConversation)
      return result.conversationId
    }
  } catch (error) {
    console.error('获取会话ID失败:', error)
    ElMessage.error('获取会话失败，请重试')
    return null
  }
}

// 获取消息记录
const getMessageList = async (conversationId) => {
  if (!conversationId) {
    return []
  }

  try {
    const messages = await listMessage({ conversationId })
    return messages || []
  } catch (error) {
    console.error('获取消息记录失败:', error)
    ElMessage.error('获取消息记录失败，请重试')
    return []
  }
}

// 选择护工
const selectCaregiver = async (caregiver) => {
  // 先清空当前消息列表
  currentMessages.value = []
  // 设置当前选中的护工
  currentCaregiver.value = caregiver

  try {
    // 获取会话ID
    const conversationId = await getConversationId(caregiver.caregiverId)
    
    if (conversationId) {
      // 保存当前会话ID
      currentConversationId.value = conversationId
      
      // 获取消息记录
      const messages = await getMessageList(conversationId)
      
      if (messages.length > 0) {
        currentMessages.value = messages
        console.log(`找到与护工 ${caregiver.name} 的会话，共 ${messages.length} 条消息`)
      } else {
        // 空消息列表，不显示默认欢迎消息
        console.log(`与护工 ${caregiver.name} 的会话没有消息记录`)
      }
    }
  } catch (error) {
    console.error('选择护工失败:', error)
    ElMessage.error('选择护工失败，请重试')
  }

  // 滚动到底部
  scrollToBottom()
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageScrollbar.value) {
      const scrollbarEl = messageScrollbar.value.$el.querySelector('.el-scrollbar__wrap')
      if (scrollbarEl) {
        scrollbarEl.scrollTop = scrollbarEl.scrollHeight
      }
    }
  })
}

// 格式化时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`
}

// 发送消息
const sendMessage = async () => {
  if (!messageInput.value.trim()) {
    ElMessage.warning('请输入消息内容')
    return
  }

  if (!currentCaregiver.value) {
    ElMessage.warning('请先选择护工')
    return
  }

  if (!currentConversationId.value) {
    ElMessage.warning('会话未建立，请重新选择护工')
    return
  }

  const currentUser = getCurrentUser()
  if (!currentUser || !currentUser.userId) {
    ElMessage.warning('未获取到用户信息，请重新登录')
    return
  }

  try {
    const messageData = {
      conversationId: currentConversationId.value,
      senderRole: 0, // 患者角色
      senderId: currentUser.userId,
      content: messageInput.value.trim(),
      timestamp: new Date().toISOString()
    }
    
    // 先添加到本地显示，提供即时反馈
    const tempMessage = {
      ...messageData,
      messageId: 'temp-' + Date.now()
    }
    currentMessages.value.push(tempMessage)
    
    // 清空输入框
    messageInput.value = ''
    
    // 滚动到底部
    scrollToBottom()
    
    // 发送到服务器
    await addMessage(messageData)
    
    // 重新获取消息列表以确保同步
    const updatedMessages = await getMessageList(currentConversationId.value)
    currentMessages.value = updatedMessages
    
    console.log('消息发送成功')
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送失败，请重试')
  }
}

onMounted(async () => {
  await getCaregiverList()
})
</script>

<style scoped>
.consultation-container {
  padding: 20px;
}

h1 {
  margin-bottom: 20px;
  font-size: 24px;
  color: #303133;
}

.chat-container {
  display: flex;
  height: calc(100vh - 180px);
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.caregiver-list {
  width: 240px;
  border-right: 1px solid #e4e7ed;
  padding: 20px;
}

.caregiver-list h3 {
  margin: 0 0 20px 0;
  font-size: 16px;
  color: #303133;
}

.search-input {
  margin-bottom: 20px;
}

.caregiver-item {
  display: flex;
  align-items: center;
  padding: 12px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.caregiver-item:hover {
  background-color: #f5f7fa;
}

.caregiver-item.active {
  background-color: #ecf5ff;
}

.caregiver-info {
  margin-left: 12px;
}

.caregiver-info .name {
  font-size: 14px;
  color: #303133;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}

.chat-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  gap: 10px;
}

.chat-placeholder {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.chat-messages {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.message-list {
  padding: 20px;
}

.message-item {
  margin-bottom: 20px;
}

.message-time {
  text-align: center;
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.message-content {
  display: flex;
  align-items: flex-start;
}

.message-content.message-right {
  flex-direction: row-reverse;
}

.message-bubble {
  margin: 0 12px;
  padding: 10px 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
  color: #303133;
  max-width: 60%;
}

.message-right .message-bubble {
  background-color: #ecf5ff;
}

.input-area {
  padding: 20px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  gap: 12px;
}

.send-btn {
  align-self: flex-end;
}
</style> 